<template>
  <div class="news-management-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <!-- 标题搜索 -->
      <input
        type="text"
        v-model="searchQuery"
        placeholder="输入新闻标题关键词"
        @keyup.enter="fetchNewsData"
      />

      <!-- 日期选择 -->
      <input type="date" v-model="queryDate" class="date-input" />

      <button class="search-btn" @click="fetchNewsData">
        <i class="icon-search"></i> 搜索
      </button>
      <button
        class="reset-btn"
        @click="resetSearch"
        v-show="hasSearchCondition"
      >
        重置
      </button>
    </div>

    <!-- 加载状态 -->
    <div class="loading-state" v-if="isLoading">
      <p>加载中...</p>
    </div>

    <!-- 表格区域 -->
    <div class="news-table-container" v-else>
      <!-- 表格标题栏 -->
      <div class="table-header">
        <div class="table-cell title-column">标题</div>
        <div class="table-cell time-column">创建时间</div>
        <div class="table-cell action-column" v-show="isAdmin">操作</div>
      </div>

      <!-- 表格内容区 -->
      <div class="table-body">
        <!-- 数据为空时显示 -->
        <div class="empty-state" v-if="newsList.length === 0">
          <p>{{ hasSearchCondition ? "没有找到匹配的新闻" : "暂无数据" }}</p>
        </div>

        <!-- 数据列表 -->
        <div class="table-row" v-for="item in newsList" :key="item.id">
          <div class="table-cell title-column">
            <a href="" @click.prevent="toNewsDetil(item.id)">{{
              item.title
            }}</a>
          </div>
          <div class="table-cell time-column">
            {{ formatDate(item.createTime) }}
          </div>
          <div class="table-cell action-column" v-show="isAdmin">
            <button class="update-btn" @click="handleUpdate(item.id)">
              修改</button
            >|
            <button
              class="delete-btn"
              @click="handleDelete(item.id)"
              :disabled="isDeleting"
            >
              <i class="icon-delete"></i> 删除
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-container" v-if="newsList.length > 0 && !isLoading">
      <button
        class="page-btn"
        :disabled="currentPage === 1 || isLoading"
        @click="goToFirstPage"
      >
        首页
      </button>

      <button
        class="page-btn"
        :disabled="currentPage === 1 || isLoading"
        @click="goToPrevPage"
      >
        上一页</button
      >

      <span class="page-info"
        >第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span
      >
      <button
        class="page-btn"
        :disabled="currentPage === totalPages || isLoading"
        @click="goToNextPage"
      >
        下一页
      </button>
      <button
        class="page-btn"
        :disabled="currentPage === totalPages || isLoading"
        @click="goToLastPage"
      >
        末页
      </button>
      <select
        v-model="pageSize"
        @change="handlePageSizeChange"
        class="page-size-select"
        :disabled="isLoading"
      >
        <option value="10">每页10条</option>
        <option value="20">每页20条</option>
        <option value="30">每页30条</option>
      </select>
    </div>
    <!-- 实现修改的表单 -->
    <div class="modal-overlay" v-if="showEditModal">
      <div class="edit-modal">
        <div class="modal-header">
          <h3>修改新闻</h3>
          <button class="close-btn" @click="closeEditModal">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="submitEditForm">
            <div class="form-group">
              <label for="edit-title">标题</label>
              <input
                type="text"
                id="edit-title"
                v-model="news.title"
                required
              />
            </div>
            <div class="form-group">
              <label for="edit-content">内容</label>
              <textarea
                id="edit-content"
                v-model="news.content"
                rows="5"
                required
              ></textarea>
            </div>
            <div class="form-actions">
              <button type="submit" class="submit-btn" :disabled="isSubmitting">
                {{ isSubmitting ? "提交中..." : "提交修改" }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "NewsListWithDateQuery",
  data() {
    return {
      newsList: [],
      searchQuery: "",
      queryDate: "", // 查询日期 yyyy-MM-dd
      currentPage: 1,
      pageSize: 10,
      totalItems: 0,
      isLoading: false,
      isDeleting: false,
      //实现修改的参数
      showEditModal: false, //表示修改框是否出现
      isSubmitting: false,
      news: {
        id: null,
        title: "",
        content: "",
      },
      isAdmin:sessionStorage.getItem('type') === '0',
    };
  },
  computed: {
    // 是否有搜索条件
    hasSearchCondition() {
      return this.searchQuery || this.queryDate;
    },
    // 总页数
    totalPages() {
      return Math.ceil(this.totalItems / this.pageSize);
    },
  },
  created() {
    this.fetchNewsData();
  },
  methods: {
    // 获取新闻数据
    async fetchNewsData() {
      this.isLoading = true;
      console.log(this.isAdmin)
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          title: this.searchQuery || undefined,
          // 日期字段需要根据后端实际接受的参数名调整
          createTime: this.queryDate || undefined,
        };

        // 移除undefined参数
        Object.keys(params).forEach(
          (key) => params[key] === undefined && delete params[key]
        );

        const response = await axios.get("/api/news/getAllNews", { params });

        this.newsList = response.data.pageInfo.list || [];
        this.totalItems = response.data.pageInfo.total || 0;
      } catch (error) {
        console.error("获取新闻数据失败:", error);
        this.$message.error(
          "获取新闻数据失败: " +
            (error.response?.data?.message || error.message)
        );
      } finally {
        this.isLoading = false;
      }
    },

    // 重置搜索条件
    resetSearch() {
      this.searchQuery = "";
      this.queryDate = "";
      this.currentPage = 1;
      this.fetchNewsData();
    },

    // 删除新闻
    async handleDelete(id) {
      const confirmDelete = confirm(`确定要删除ID为 ${id} 的新闻吗？`);
      if (!confirmDelete) return;

      this.isDeleting = true;
      try {
        await axios.delete(`/api/news/deleteNewsById/${id}`);
        this.$message.success("删除成功");
        this.fetchNewsData(); // 刷新列表
      } catch (error) {
        console.error("删除失败:", error);
        this.$message.error(
          "删除失败: " + (error.response?.data?.message || error.message)
        );
      } finally {
        this.isDeleting = false;
      }
    },

    //修改新闻回显
    async handleUpdate(id) {
      this.isLoading = true;
      try {
        const response = await axios.get(`/api/news/getNewsById/${id}`);
        this.news = {
          id: response.data.news.id,
          title: response.data.news.title,
          content: response.data.news.content,
        };
        this.showEditModal = true;
      } catch (error) {
        console.error("获取新闻详情失败:", error);
        this.$message.error(
          "获取新闻详情失败: " +
            (error.response?.data?.message || error.message)
        );
      } finally {
        this.isLoading = false;
      }
    },

    // 提交修改表单
    async submitEditForm() {
      this.isSubmitting = true;
      try {
        console.log(this.news);
        const response = await axios.post("/api/news/updateNews", this.news);
        console.log(response.data);
        this.$message.success("修改成功");
        this.closeEditModal();
        this.fetchNewsData(); // 刷新列表
      } catch (error) {
        console.error("修改失败:", error);
        this.$message.error(
          "修改失败: " + (error.response?.data?.message || error.message)
        );
      } finally {
        this.isSubmitting = false;
      }
    },

    //前往新闻详情
    toNewsDetil(id) {
      this.$router.push(`/NewsDetil/${id}`);
    },

    // 关闭修改表单，清空数据
    closeEditModal() {
      this.showEditModal = false;
      this.news = {
        id: null,
        title: "",
        content: "",
      };
    },

    // 分页导航
    goToPrevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.fetchNewsData();
      }
    },

    goToFirstPage() {
      if (this.currentPage > 1) {
        this.currentPage = 1;
        this.fetchNewsData();
      }
    },

    goToNextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.fetchNewsData();
      }
    },
    goToLastPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage = this.totalPages;
        this.fetchNewsData();
      }
    },

    // 每页条数变化
    handlePageSizeChange() {
      this.currentPage = 1;
      this.fetchNewsData();
    },

    // 内容截断
    truncateContent(content) {
      const maxLength = 20;
      return content.length > maxLength
        ? `${content.slice(0, maxLength)}...`
        : content;
    },

    // 日期格式化
    formatDate(dateString) {
      if (!dateString) return "";
      return new Date(dateString).toLocaleDateString();
    },
  },
};
</script>

<style scoped>
/* 搜索栏样式 */
.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  margin-left: 200px;
  padding-left: 400px;

  background-color: #f5f5f5;
  border-radius: 4px;
  align-items: center;
}

.search-bar input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.date-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  width: 160px;
}

.search-btn,
.reset-btn {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.search-btn {
  background-color: #1890ff;
  color: white;
}

.reset-btn {
  background-color: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
}

/* 加载状态 */
.loading-state {
  padding: 40px 0;
  text-align: center;
  color: #666;
  font-size: 16px;
}

/* 表格样式 */
.news-table-container {
  width: 70%;
  min-width: 800px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.table-header {
  display: flex;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
  font-weight: bold;
  color: #333;
}

.table-row {
  display: flex;
  border-bottom: 1px solid #e0e0e0;
  transition: background-color 0.2s;
}

.table-row:hover {
  background-color: #f9f9f9;
}

.table-cell {
  padding: 12px 16px;
  line-height: 1.5;
  word-break: break-all;
}

.id-column {
  width: 80px;
  flex-shrink: 0;
  color: #666;
}

.title-column {
  flex: 1;
  min-width: 40%;
}

.content-column {
  flex: 2;
  min-width: 300px;
  color: #666;
}

.time-column {
  width: 40%;
  flex-shrink: 0;
  color: #999;
}

.action-column {
  width: 140px;
  flex-shrink: 0;
  text-align: center;
}

.content-text {
  display: inline-block;
  max-width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.delete-btn {
  padding: 6px 10px;
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  align-items: center;
  transition: background-color 0.2s;
}

.delete-btn:hover {
  background-color: #f5222d;
}

.delete-btn:disabled {
  background-color: #ffccc7;
  cursor: not-allowed;
}

.update-btn {
  padding: 6px 10px;
  background-color: green;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  align-items: center;
  transition: background-color 0.2s;
}
.empty-state {
  padding: 40px 0;
  text-align: center;
  color: #999;
  border-bottom: 1px solid #e0e0e0;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  gap: 15px;
  padding: 10px;
}

.page-btn {
  padding: 6px 12px;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.page-btn:hover:not(:disabled) {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: #666;
}

.page-size-select {
  padding: 6px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
}

/* 图标样式 */
.icon-search::before {
  content: "🔍";
}

.icon-reset::before {
  content: "🔄";
}

/*修改框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.edit-modal {
  background-color: white;
  border-radius: 8px;
  width: 650px;
  max-width: 90%;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: rgba(0, 0, 0, 0.85);
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: rgba(0, 0, 0, 0.45);
}

.close-btn:hover {
  color: rgba(0, 0, 0, 0.75);
}

.modal-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.form-group input,
.form-group textarea {
  width: 90%;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  resize: vertical;
  min-height: 100px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 24px;
}

.cancel-btn {
  padding: 8px 16px;
  background-color: #f5f5f5;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn:hover {
  background-color: #e6e6e6;
}

.submit-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.submit-btn:hover {
  background-color: #40a9ff;
}

.submit-btn:disabled {
  background-color: #bae7ff;
  cursor: not-allowed;
}
</style>